const { contextBridge, ipcRenderer } = require('electron')

// 暴露安全的接口给渲染进程
contextBridge.exposeInMainWorld('electronAPI', {
  // 数据库操作
  getExpenses: (filters) => ipcRenderer.invoke('db-get-expenses', filters),
  addExpense: (expense) => ipcRenderer.invoke('db-add-expense', expense),
  updateExpense: (id, expense) => ipcRenderer.invoke('db-update-expense', id, expense),
  deleteExpense: (id) => ipcRenderer.invoke('db-delete-expense', id),
  getCategories: () => ipcRenderer.invoke('db-get-categories'),
  addCategory: (category) => ipcRenderer.invoke('db-add-category', category),
  getStatistics: (period) => ipcRenderer.invoke('db-get-statistics', period),

  // 智能服务
  analyzeExpenses: (expenses) => ipcRenderer.invoke('ai-analyze-expenses', expenses),
  suggestCategory: (description) => ipcRenderer.invoke('ai-suggest-category', description),
  generateReport: (data) => ipcRenderer.invoke('ai-generate-report', data),

  // 导出功能
  exportToCSV: (data) => {
    const csv = convertToCSV(data)
    const blob = new Blob([csv], { type: 'text/csv' })
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `expenses_${new Date().toISOString().split('T')[0]}.csv`
    a.click()
    window.URL.revokeObjectURL(url)
    return Promise.resolve('导出成功')
  },

  // 菜单事件监听
  onMenuAction: (callback) => {
    ipcRenderer.on('menu-new-record', callback)
    ipcRenderer.on('menu-import-data', callback)
    ipcRenderer.on('menu-export-data', callback)
  },

  // 移除监听器
  removeAllListeners: (channel) => {
    ipcRenderer.removeAllListeners(channel)
  },

  // 工具函数
  utils: {
    formatCurrency: (amount) => {
      return new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY'
      }).format(amount)
    },
    formatDate: (date) => {
      return new Date(date).toLocaleDateString('zh-CN')
    },
    exportToCSV: (data, filename) => {
      const csv = convertToCSV(data)
      const blob = new Blob([csv], { type: 'text/csv' })
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = filename
      a.click()
      window.URL.revokeObjectURL(url)
    }
  }
})

// 数据转换辅助函数
function convertToCSV(data) {
  if (!data || data.length === 0) return ''
  
  const headers = Object.keys(data[0])
  const csvHeaders = headers.join(',')
  
  const csvRows = data.map(row => {
    return headers.map(header => {
      const value = row[header]
      // 处理包含逗号或引号的值
      if (typeof value === 'string' && (value.includes(',') || value.includes('"'))) {
        return `"${value.replace(/"/g, '""')}"`
      }
      return value
    }).join(',')
  })
  
  return [csvHeaders, ...csvRows].join('\n')
}